package com.zhongyewx.teachercert.base;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;

import com.zhongyewx.teachercert.framework.exception.MvpViewNotAttachedException;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class ZYBasePresenter<T extends IBaseView> implements LifecycleObserver {
    public static final int ON_CREATE = 1;
    public static final int ON_START = 2;
    public static final int ON_RESUME = 3;
    public static final int ON_PAUSE = 4;
    public static final int ON_STOP = 5;
    public static final int ON_DESTROY = 6;
    public int tag;
    protected T mRootView;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    public void attachView(T mRootView){
        this.mRootView = mRootView;
    }

    public void detachView(){
        mRootView = null;
        if (!compositeDisposable.isDisposed()) {
            compositeDisposable.clear();
        }
    }

    protected void addSubscription(Disposable disposable) {
        compositeDisposable.add(disposable);
    }

    protected boolean isOnResume(){
        if (tag != ON_RESUME){
            return false;
        }
        return true;
    }

    protected void checkViewAttach(){
        if (mRootView == null) throw new MvpViewNotAttachedException();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCrete(){
        tag = ON_CREATE;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart(){
        tag = ON_START;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume(){
        tag = ON_RESUME;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause(){
        tag = ON_PAUSE;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop(){
        tag = ON_STOP;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy(){
        tag = ON_DESTROY;
    }
}
